<?php

namespace App\Http\Controllers\Web\V1;

use App\Http\Controllers\Controller;
use App\Models\Question;
use App\Models\StudentResult;
use App\Models\TestList;
use App\Transformers\Web\ResultTransformer;
use Dingo\Api\Http\Response;

class ResultController extends Controller
{
    /**
     * 我的成绩列表
     *
     * @return Response
     */
    public function index()
    {
        $result = StudentResult::query()
            ->where('user_id', $this->adminUser()->id())
            ->select('all_num','success_num','error_num','fraction','already_num','end_time','submit_type','examination_id')
            ->with('examination:id,name,type,start_time')
            ->paginate($this->pageLimit());

        return $this->response->paginator($result, new ResultTransformer());
    }

    /**
     *我的成绩详情
     *
     * @param StudentResult $ressult
     * @return array|Response
     */
    public function show(StudentResult $result)
    {
        $ids = [];

        // 获取题目id

        if (empty($result->content)){
           return $this->response->errorNotFound();
        }
        foreach ($result->content as $k => $item) {
            array_push($ids,$k);
        }

        $questions = Question::select('id', 'type', 'title', 'content', 'answer', 'success_answer', 'fraction', 'analysis')
            ->whereIn('id', $ids)->get()->toArray();

        $data = [];

        foreach ($questions as $question) {
            foreach ($result->content as $k => $item) {
                if ($k == $question['id']) {
                    $question['student_answer'] = $item;
                }
            }
            array_push($data, $question);
        }

        $examination = $result->examination;
        $user = $result->user;

        return $this->response->array([
            'examination' => $examination,
            'data' => $data,
            'user' => $user
        ]);

    }
}
